layui.define(['jquery', 'layer', 'mMenu', 'mTab'], function(exports) {
    var $ = layui.$,
        layer = layui.layer,
        mMenu = layui.mMenu,
        mTab = layui.mTab,
        device = layui.device();

    if (!/http(s*):\/\//.test(location.href)) {
        var tips = "请先将项目部署至web容器（Apache/Tomcat/Nginx/IIS/等），否则部分数据将无法显示";
        return layer.alert(tips);
    }
    if (device.ie && device.ie < 10) {
        view.error('IE' + device.ie + '下访问可能不佳，推荐使用：Chrome / Firefox / Edge 等高级浏览器', {
          offset: 'auto'
          , id: 'LAY_errorIE'
        });
      }
    var mAdmin = {
        render: function () {
            window.mAdmin = mAdmin
            mAdmin.checkLogin(function(resp) {
                mAdmin.renderLogo(setter.logoInfo)
                mAdmin.renderHome(setter.homeInfo)
                mAdmin.renderTheme()
                mAdmin.renderLayout()
                mMenu.render()
                mTab.render()
                mAdmin.listen()
            })
        },
        renderLogo: function(data) {
            var ologo = $('.layui-logo')
            ologo.find('.logo-img').attr('src', data.image);
            ologo.find('.logo-title').html(data.title)
        },
        renderHome: function(data) {
            $('#homeTabTitleId')
                .html('<span class="tab-pre-icon"></span><span class="disable-close" locale-html="menu.' + data.i18n + '">' + data.title + '</span>')
                .attr('lay-id', data.href);
            $('#homeTabIframeId')
                .html('<iframe src="' + data.href + '" class="multi-tab-iframe"></iframe>');
        },
        renderTheme: function() {
            var themeId = getTheme()
            mAdmin.events.changeTheme(themeId);
        },
        renderLayout: function() {
            if (getData(setter.store.sideShrink) === true) {
                $(setter.containerCls).addClass('layui-side-shrink')
                $('.layui-side-flexible').children('a').attr('locale-title', 'index.side.spread')
            }
            if (getData(setter.store.headerHidden) === true) {
                $(setter.containerCls).addClass('layout-header-hidden')
            }
            if (getData(setter.store.footerHidden) !== true) {
                $(setter.containerCls).removeClass('layout-footer-hidden')
            }
        },
        /**
         * 验证是否登录
         * @param {*} callback 
         */
        checkLogin: function(callback) {
            callback && callback()
        },
        listen: function () {
            // event
            $('body').on('click', '*[lay-layout-event]', function() {
                var othis = $(this),
                    attrEvent = othis.attr('lay-layout-event');
                if (othis.hasClass('layui-btn-disabled')) {
                    return;
                }
                mAdmin.events[attrEvent] && mAdmin.events[attrEvent].call(this, othis);
            })
            // tips
            $('body').on('mouseenter', '*[lay-tips]', function() {
                var othis = $(this);
                if (!$(setter.containerCls).hasClass('layui-side-shrink')) {
                    var oparent = othis.parent()
                    if (oparent.hasClass('layui-nav-item') || 'DD' === oparent[0].tagName) {
                        return
                    }
                }
                var tips = othis.attr('lay-tips'), 
                    offset = othis.attr('lay-offset'),
                    direction = othis.attr('lay-direction') || 1;
                var index = layer.tips(tips, this, {
                    tips: direction,
                    time: -1,
                    success: function (layer0, index) {
                        if (offset) {
                            layer0.css('margin-left', offset + 'px');
                        }
                    }
                })
                othis.data('index', index);
            }).on('mouseleave', '*[lay-tips]', function () {
                layer.close($(this).data('index'));
            });
            // side-user-area
            $('body').on('mouseenter', '.side-user-pic,.side-user-text .title', function(event) {
                var $dropdown = $('.side-user-dropdown-nav')
                if ($dropdown.is(":hidden")) {
                    $dropdown.fadeIn().css(
                        {
                            top: event.clientY,
                            left: event.clientX
                        }
                    )
                }
            }).on('mouseleave', '.side-user-pic,.side-user-text .title', function() {
                var $dropdown = $('.side-user-dropdown-nav')
                if ($dropdown.is(":visible")) {
                    setTimeout(function(){
                        $dropdown.fadeOut()
                    }, 2000)
                }
            });
        },
        events: {
            /**
             * 刷新页面
             * @param {*} othis 
             */
            refresh: function(othis) {
                $(".layui-tab-item.layui-show").find("iframe")[0].contentWindow.location.reload();
            },
            resize: function(cls, storeName, event, containerSelector = setter.containerCls) {
                $(containerSelector).toggleClass(cls)
                var hasCls = $(containerSelector).hasClass(cls)
                setData(storeName, hasCls)
                mTab.dispatchMessage('resize', {event: event, value: hasCls})
            },
            changeTheme: function(themeId) {
                setData(setter.store.bgColorId, themeId)
                $(setter.containerCls).removeClass(function(index, className) {
                    return (className.match (/(^|\s)layui-theme-\S+/g) || []).join(' ');
                }).addClass('layui-theme-' + themeId)
                mTab.dispatchMessage('changeTheme', themeId)
            },
            switchLanguage: function() {
                var langId = $(this).data('lang')
                if (getData('lang') !== langId) {
                    I18n.setLang(langId)
                    mTab.dispatchMessage('switchLanguage', langId)
                }
            },
            /**
             * 收缩左侧菜单
             * @param {*} othis 
             */
            toggleSideFlexible: function(othis) {
                mAdmin.events.resize('layui-side-shrink', setter.store.sideShrink, 'toggleSide')
                var flag = $(setter.containerCls).hasClass('layui-side-shrink')
                othis.children('a').attr('title', I18n.localeValue('index.side.' + (flag? 'spread': 'shrink')))
            },
            /**
             * 头部显示/隐藏
             * @param {*} othis 
             */
            toggleHeaderHidden: function(othis) {
                mAdmin.events.resize('layout-header-hidden', setter.store.headerHidden, 'toggleHeader')
            },
            /**
             * 底部显示/隐藏
             * @param {*} othis 
             */
            toggleFooterHidden: function(othis) {
                mAdmin.events.resize('layout-footer-hidden', setter.store.footerHidden, 'toggleFooter')
            },
            /**
             * 退出
             * @param {*} othis 
             */
            logout: function(othis) {
                layer.confirm('确认退出?', function() {
                    window.location.href = setter.loginHref
                })
            },
            /**
             * 设置
             * @param {*} othis 
             */
            systemSetting: function(othis) {
                var clientHeight = document.documentElement.clientHeight;
                if (getData(setter.store.headerHidden) !== true) {
                    clientHeight -= 60;
                }
                layer.open({
                    type: 2,
                    title: false,
                    closeBtn: 0,
                    shade: 0.2,
                    anim: 2,
                    shadeClose: true,
                    area: ['340px', clientHeight + 'px'],
                    offset: 'rb',
                    content: [setter.settingHref, 'no'],
                    success: function (index, layero) {
                    },
                    end: function () {
                    }
                })
            }
        }
    };
    exports('mAdmin', mAdmin);
})